package com.linwankaifa.linwancunyi.util;

import android.util.Base64;

import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonParser;

import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;

public class JsonTransformation {//json转换,以实体Manager为例
    static byte[] textByte = new byte[0];
    static String endodeStr;
    static String decodeStr;

    public static <T> String objectToJson(T clazz)//object to json
    {
        Gson gson = new Gson();
        endodeStr = gson.toJson(clazz);
        try {
            textByte = endodeStr.getBytes("UTF-8");
        } catch (
                UnsupportedEncodingException e) {
            e.printStackTrace();
            return "";
        }
        return Base64.encodeToString(textByte, Base64.NO_WRAP);
    }

    public static <T> T jsonToObject(String gsonStr, Class<T> clazz)//json to object
    {
        Gson gson = new Gson();
        try {
            decodeStr = new String(Base64.decode(gsonStr.toString().replace("\r\n", ""), Base64.DEFAULT), "utf-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
            return null;
        }
        return gson.fromJson(decodeStr, clazz);
    }

    public static <T> String listToJson(List<T> list)//list to json
    {

        Gson gson = new Gson();
        endodeStr = gson.toJson(list);
        try {
            textByte = endodeStr.getBytes("UTF-8");
        } catch (
                UnsupportedEncodingException e) {
            e.printStackTrace();
            return "";
        }
        return Base64.encodeToString(textByte, Base64.NO_WRAP);
    }


    public static <T> List<T> jsonToList(String gsonStr, Class<T> clazz)//json to list
    {
        try {
            decodeStr = new String(Base64.decode(gsonStr.toString().replace("\r\n", ""), Base64.DEFAULT), "utf-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
            return null;
        }
        List<T> list = new ArrayList<T>();
        try {
            Gson gson = new Gson();
            JsonArray arry = new JsonParser().parse(decodeStr).getAsJsonArray();
            for (JsonElement jsonElement : arry) {
                list.add(gson.fromJson(jsonElement, clazz));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return list;

    }


}
